package com.ytlz.dmcs.model.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ytlz.dmcs.common.TreeNodeInfo;
import com.ytlz.dmcs.model.system.dao.SysMenuDao;
import com.ytlz.dmcs.model.system.entity.SysMenu;
import com.ytlz.dmcs.model.system.service.MenuService;

@Service
public class MenuServiceImpl implements MenuService {
	@Autowired
	private SysMenuDao sysMenuDao;

	@Override
	public List<Map<String, Object>> getAllMenus() {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		List<SysMenu> parentMenus = sysMenuDao.findByParentId(null);
		if (parentMenus.size() > 0) {
			for (SysMenu parent : parentMenus) {
				Map<String, Object> menu = new HashMap<String, Object>();
				menu.put("id", parent.getId());
				menu.put("text", parent.getText());
				List<SysMenu> subMenus = sysMenuDao.findByParentId(parent.getId());
				if (subMenus != null && subMenus.size() > 0) {
					List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
					for (SysMenu submenu : subMenus) {
						Map<String, Object> child = new HashMap<String, Object>();
						child.put("id", submenu.getId());
						child.put("text", submenu.getText());
						Map<String, Object> attributes = new HashMap<String, Object>();
						attributes.put("url", submenu.getUrl() == null ? "#" : submenu.getUrl());
						child.put("attributes", attributes);
						children.add(child);
					}
					menu.put("children", children);
				}
				result.add(menu);
			}
		}
		return result;
	}

	@Override
	public List<TreeNodeInfo> getMenus() {
		List<TreeNodeInfo> result = new ArrayList<TreeNodeInfo>();
		List<SysMenu> parentMenus = sysMenuDao.findByParentId(null);
		if (parentMenus.size() > 0) {
			for (SysMenu parent : parentMenus) {
				TreeNodeInfo menu = new TreeNodeInfo();
				menu.setId(parent.getId());
				menu.setText(parent.getText());
				List<SysMenu> subMenus = sysMenuDao.findByParentId(parent.getId());
				if (subMenus != null && subMenus.size() > 0) {
					List<TreeNodeInfo> children = new ArrayList<TreeNodeInfo>();
					for (SysMenu submenu : subMenus) {
						TreeNodeInfo child = new TreeNodeInfo();
						child.setId(submenu.getId());
						child.setText(submenu.getText());
						Map<String, Object> attributes = new HashMap<String, Object>();
						attributes.put("url", submenu.getUrl() == null ? "#" : submenu.getUrl());
						child.setAttributes(attributes);
						children.add(child);
					}
					menu.setChildren(children);
				}
				result.add(menu);
			}
		}
		return result;
	}
}
